<?php
/*
 * 单品不定期阶梯优惠
 * 不修改商品价格，已优惠券的方式扣减总价
 *
 * 关于 code 的说明
 * INSERT INTO `extension` SET `type`='total',`code`='slippers';
 * INSERT INTO `setting` SET `store_id`='0',`code`='slippers',`key`='slippers_status',`value`='1',`serialized`='0';//确保优惠记录可用
 * INSERT INTO `setting` SET `store_id`='0',`code`='slippers',`key`='slippers_sort_order',`value`='3',`serialized`='0';//优惠记录排序用，升序排列，没什么实际作用
 * total排序说明：1是商品小计，2是在线支付优惠，3是免运费，4是优惠券，100是订单总计价格。超过99显示可能会很奇怪，不要超过99。看上去可以重复，支持无限多的单品优惠
 *
 * 历史优惠记录
 ****************************************************
 * 优惠时间：2017/10/01 000000 ～ 2017/11/19 235959
 * 商品编码：33020400010
 * 商品名称：慈北防滑室内棉拖鞋8998
 * 商品原价：6.9
 * 优惠策略：总价 >= 10000，限购 800 双，优惠价5.9
 *           总价 >= 5000，限购 480 双，优惠价5.9
 *           总价 >= 3000，限购 240 双，优惠价5.9
 ****************************************************
 * 优惠时间：2017/11/18 110000 ～ 2017/12/18 235959
 * 商品编码：26070400240
 * 商品名称：洪英 Z印花卡通款电暖手宝 0708
 * 商品原价：12
 * 优惠策略：总价 >= 5000，限购 200 个，优惠价9.9
 *           总价 >= 3000，限购 100 个，优惠价9.9
 *           总价 >= 1000，限购 50 个，优惠价9.9
 ****************************************************
 * 优惠时间：2017/12/07 110000 ～ 2017/12/31 235959
 * 商品编码：21010322310 / 21010322320
 * 商品名称：迪美达 钢带子弹头500ml NCDZ-D500-2（蓝色）/ 迪美达 钢带子弹头500ml NCDZ-D500-2（蓝色）
 * 商品原价：12.9 / 12.9
 * 优惠策略：总价 >= 5000，限购 100 个，优惠价9.9
 *           总价 >= 3000，限购 50 个，优惠价10.9
 *           总价 >= 1000，限购 25 个，优惠价10.9
 */
 class ModelTotalSlippers extends Model {
    private $_discountList;//优惠单品数组

    /*
     * 参数说明：
     * $this->_discountList = array(
     *     array(
     *         'title' => 优惠名称（显示在页面上）,
     *         'sortOrder' => 显示顺序,
     *         'startDate' => 开始时间（时间戳）,
     *         'endDate' => 结束时间（时间戳）,
     *         'productCode' => array(
     *             11位商品编码（支持多个）,
     *         ),
     *         'totalModel' => 总价模式（ALL/all表示 参与阶梯判断的价格 = 购物车商品总价 - 所有有效期内优惠单品的总价 ; 其他内容表示 参与阶梯判断的价格 = 购物车商品总价 - 本优惠单品的总价）,
     *         'priceModel' => 优惠模式（当pCode为多个数组且价格不一样时有效，DESC/desc表示先优惠贵的商品再优惠便宜的；其他内容表示先优惠便宜的再优惠贵的）,
     *         'stepPriceList' => array(
     *             customerGroupId => array(
     *                 array('minTotal'=>阶梯价, 'maxQty'=>限购数量, 'sPrice'=>优惠价格),
     *             ),
     *         ),
     *     ),
     * );
     */
    protected function _initDiscountList() {
        $this->_discountList = array(
            array(
                'title' => '拖鞋优惠',
                'sortOrder' => 3,
                'startDate' => strtotime('2017-10-01 00:00:00'),
                'endDate' => strtotime('2017-11-19 23:59:59'),
                'productCode' => array('33020400010'),
                'totalModel' => 'ALL',
                'priceModel' => 'DESC',
                'stepPriceList' => array(
                    1 => array(
                        array('minTotal'=>10000, 'maxQty'=>800, 'sPrice'=>5.9),
                        array('minTotal'=>5000, 'maxQty'=>480, 'sPrice'=>5.9),
                        array('minTotal'=>3000, 'maxQty'=>240, 'sPrice'=>5.9),
                    ),
                ),
            ),
            array(
                'title' => '暖手宝优惠',
                'sortOrder' => 4,
                'startDate' => strtotime('2017-11-18 11:00:00'),
                'endDate' => strtotime('2017-12-18 23:59:59'),
                'productCode' => array('26070400240'),
                'totalModel' => 'ALL',
                'priceModel' => 'DESC',
                'stepPriceList' => array(
                    1 => array(
                        array('minTotal'=>5000, 'maxQty'=>200, 'sPrice'=>9.9),
                        array('minTotal'=>3000, 'maxQty'=>100, 'sPrice'=>9.9),
                        array('minTotal'=>1000, 'maxQty'=>50, 'sPrice'=>9.9),
                    ),
                ),
            ),
            array(
                'title' => '保温杯优惠',
                'sortOrder' => 4,
                'startDate' => strtotime('2017-12-07 00:00:00'),
                'endDate' => strtotime('2017-12-31 23:59:59'),
                'productCode' => array(
                    '21010322310',
                    '21010322320',
                ),
                'totalModel' => 'ALL',
                'priceModel' => 'ASC',
                'stepPriceList' => array(
                    1 => array(
                        array('minTotal'=>5000, 'maxQty'=>100, 'sPrice'=>9.9),
                        array('minTotal'=>3000, 'maxQty'=>50, 'sPrice'=>10.9),
                        array('minTotal'=>1000, 'maxQty'=>25, 'sPrice'=>10.9),
                    ),
                ),
            ),
            array(
                'title' => '鸭嘴壶',
                'sortOrder' => 4,
                'startDate' => strtotime('2018-03-07 00:00:00'),
                'endDate' => strtotime('2018-04-30 23:59:59'),
                'productCode' => array(
                    '21021001600'
                ),
                'totalModel' => 'ALL',
                'priceModel' => 'ASC',
                'stepPriceList' => array(
                    1 => array(
                        array('minTotal'=>2000, 'maxQty'=>180, 'sPrice'=>3.9)
                    ),
                ),
            ),
        );
    }

    public function getTotal(&$total_data, &$total, &$taxes) {
        $this->_initDiscountList();
        $discountList = array();
        $now = time();
        $totalPriceInCart = $this->cart->getTotal();
        $customerGroupId = $this->customer->getGroupId();
        //判断优惠是否生效，初始化总价
        foreach ($this->_discountList as $discountInfo) {
            if (($now >= $discountInfo['startDate'] && $now <= $discountInfo['endDate']) && array_key_exists($customerGroupId, $discountInfo['stepPriceList'])) {
                $discountList[] = $discountInfo;
                $tpInCartList[] = array(
                    'amount' => $totalPriceInCart,
                    'model' => strtolower($discountInfo['totalModel']),
                );
            }
        }
        //初始化数据
        foreach ($discountList as $k=>$discountInfo) {
            $cpList = $this->cart->getProducts();
            $qtyWithPrice = array();
            foreach ($cpList as $cpInfo) {
                if (in_array($cpInfo['option'][0]['product_code'], $discountInfo['productCode'])) {
                    // var_dump($cpInfo['option'][0]['product_code']);
                    $qtyWithPrice[(string)$cpInfo['price']] += $cpInfo['quantity'];
                    foreach ($tpInCartList as $kk=>$tpInCartInfo) {
                        if ('all' == $tpInCartInfo['model'] || $kk == $k) {
                            $tpInCartList[$kk]['amount'] -= $cpInfo['total'];
                        }

                    }
                }
            }
            if ('desc' == strtolower($discountInfo['priceModel'])) {
                krsort($qtyWithPrice, SORT_NUMERIC);
            }else{
                ksort($qtyWithPrice, SORT_NUMERIC);
            }
            $discountInCart[$k] = $qtyWithPrice;
        }
        //计算优惠金额
        foreach ($discountList as $k=>$discountInfo) {
            $discountAmount = 0;
            foreach ($discountInfo['stepPriceList'][$customerGroupId] as $stepPrice) {
                if ($tpInCartList[$k]['amount'] >= $stepPrice['minTotal']) {
                    $discountQty = $stepPrice['maxQty'];
                    foreach ($discountInCart[$k] as $price=>$qty) {
                        if ($discountQty > 0) {
                            $discountAmount += ($stepPrice['sPrice']-$price)*min($discountQty, $qty);
                            $discountQty -= $qty;
                        }
                    }
                    $total += $discountAmount;
                    break;
                }
            }
            if ($discountAmount < 0) {
                $total_data[] = array(
                    'code'       => 'slippers',//这个值涉及到数据库和文件名，不建议修改
                    'title'      => $discountInfo['title'],
                    'value'      => $discountAmount,
                    'sort_order' => $discountInfo['sortOrder'],
                );
            }
        }
    }

    /* 参与阶梯判断的价格 = 购物车商品总价 - 所有有效期内优惠单品的总价 
    public function getTotal(&$total_data, &$total, &$taxes) {
        $this->_initDiscountList();
        $now = time();
        $tpInCartWithoutPCode = $this->cart->getTotal();
        foreach ($this->_discountList as $discountInfo) {
            if ($now >= $discountInfo['startDate'] && $now <= $discountInfo['endDate']) {
                $cpList = $this->cart->getProducts();
                foreach ($cpList as $cpInfo) {
                    if ($cpInfo['option'][0]['product_code'] == $discountInfo['productCode']) {
                        $priceInCart[$discountInfo['productCode']] = $cpInfo['price'];
                        $qtyInCart[$discountInfo['productCode']] = $cpInfo['quantity'];
                        $tpInCartWithoutPCode -= $cpInfo['total'];
                    }
                }
            }
        }
        foreach ($this->_discountList as $discountInfo) {
            if ($now >= $discountInfo['startDate'] && $now <= $discountInfo['endDate']) {
                foreach ($discountInfo['stepPriceList'] as $stepPrice) {
                    if ($tpInCartWithoutPCode >= $stepPrice['minTotal']) {
                        $discountAmount = ($stepPrice['sPrice']-$priceInCart[$discountInfo['productCode']]) * min($stepPrice['maxQty'], $qtyInCart[$discountInfo['productCode']]);
                        $total += $discountAmount;
                        break;
                    }
                }
                if ($discountAmount < 0) {
                    $total_data[] = array(
                        'code'       => 'slippers',//这个值涉及到数据库和文件名，不建议修改
                        'title'      => $discountInfo['title'],
                        'value'      => $discountAmount,
                        'sort_order' => $discountInfo['sortOrder'],
                    );
                }
            }
        }
    }
    // */

    /* 参与阶梯判断的价格 = 购物车商品总价 - 本优惠单品的总价
    public function getTotal(&$total_data, &$total, &$taxes) {
        $this->_initDiscount();
        $now = time();
        foreach ($this->_discountList as $discountInfo) {
            if ($now >= $discountInfo['startDate'] && $now <= $discountInfo['endDate']) {
                $tpInCart = $this->cart->getTotal();
                $cpList = $this->cart->getProducts();
                foreach ($cpList as $cpInfo) {
                    if ($cpInfo['option'][0]['product_code'] == $discountInfo['productCode']) {
                        $priceInCart = $cpInfo['price'];
                        $qtyInCart = $cpInfo['quantity'];
                        $tpInCartWithoutPCode = $tpInCart-$cpInfo['total'];
                    }
                }
                foreach ($discountInfo['stepPriceList'] as $stepPrice) {
                    if ($tpInCartWithoutPCode >= $stepPrice['minTotal']) {
                        $discountAmount = ($stepPrice['sPrice']-$priceInCart) * min($stepPrice['maxQty'], $qtyInCart);
                        $total += $discountAmount;
                        break;
                    }
                }
                if ($discountAmount < 0) {
                    $total_data[] = array(
                        'code'       => 'slippers',//这个值涉及到数据库和文件名，不建议修改
                        'title'      => $discountInfo['title'],
                        'value'      => $discountAmount,
                        'sort_order' => $discountInfo['sortOrder'],
                    );
                }
            }
        }
    }
    // */

    /* 原始版本
    public function getTotal(&$total_data, &$total, &$taxes) {

        if(time()>strtotime('2017-11-18 00:00:00') && time()<strtotime('2017-12-18 23:59:59')){

            $temp_total = $this->cart->getTotal();

            $price = 0;

            $quantity = 0;

            $reduce_total = 0;

            if($this->cart->hasProducts()){

                foreach($this->cart->getProducts() as $val){

                    if($val['option'][0]['product_code'] == '33020400010'){

                        $temp_total -= $val['total'];

                        $price = $val['price'];

                        $quantity = $val['quantity'];

                        break;

                    }

                }

                if($temp_total >= 3000 && $temp_total < 5000){

                    if($quantity <= 240 && $quantity > 0){

                        $price -= 5.9;

                        $price = $price < 0?0:$price;

                        $reduce_total = $quantity * $price;

                        $total -= $reduce_total;

                    }elseif($quantity > 240){

                        $price -= 5.9;

                        $price = $price < 0?0:$price;

                        $reduce_total = 240 * $price;

                        $total -= $reduce_total;

                    }

                }elseif($temp_total >= 5000 && $temp_total < 10000){

                    if($quantity <= 480 && $quantity > 0){

                        $price -= 5.9;

                        $price = $price < 0?0:$price;

                        $reduce_total = $quantity * $price;

                        $total -= $reduce_total;

                    }elseif($quantity > 480){

                        $price -= 5.9;

                        $price = $price < 0?0:$price;

                        $reduce_total = 480 * $price;

                        $total -= $reduce_total;

                    }

                }elseif($temp_total >= 10000){

                    if($quantity <= 800 && $quantity > 0){

                        $price -= 5.5;

                        $price = $price < 0?0:$price;

                        $reduce_total = $quantity * $price;

                        $total -= $reduce_total;

                    }elseif($quantity > 800){

                        $price -= 5.5;

                        $price = $price < 0?0:$price;

                        $reduce_total = 800 * $price;

                        $total -= $reduce_total;

                    }

                }

                if($reduce_total != 0){

                    $total_data[] = array(
                        'code'       => 'slippers',
                        'title'      => '拖鞋优惠',
                        'value'      => (0 - $reduce_total),
                        'sort_order' => $this->config->get('slippers_sort_order')
                    );

                }

            }

        }

    }
*/
}
